package 多线程08_lock对象;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName: TestThreadLock01
 * @Author: AllenSun
 * @Date: 2022/3/23 下午10:53
 */
public class TestThreadAwaitSignal {

    public static String nowTime() {
        return new SimpleDateFormat("HH:mm:ss").format(new Date());
    }

    public static void log(String msg) {
        System.out.printf("%s %s %s %n",nowTime(),Thread.currentThread().getName(),msg);
    }

    public static void main(String[] args) {
        Lock lockDemo = new ReentrantLock();

        Condition condition = lockDemo.newCondition();

        Thread thread1 = new Thread() {
            public void run() {
                boolean lockResult = false;
                try {
                    log("线程启动");
                    log("试图占有对象：lock");

                    lockDemo.lock();

                    log("占有对象：lock");
                    log("进行5秒的业务操作");
                    Thread.sleep(5000);
                    log("临时释放对象 lock， 并等待");
                    condition.await();
                    log("重新占有对象 lock，并进行5秒的业务操作");
                    Thread.sleep(5000);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    log("释放对象：lock");
                    lockDemo.unlock();
                }
                log("线程结束");
            }
        };
        thread1.setName("thread01");
        thread1.start();


        try {
            //先让t1飞2秒
            Thread.sleep(2000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }


        Thread thread2 = new Thread() {
            public void run() {
                boolean lockResult = false;
                try {
                    log("线程启动");
                    log("试图占有对象：lock");

                    lockDemo.lock();

                    log("占有对象：lock");
                    log("进行5秒的业务操作");
                    Thread.sleep(5000);
                    log("唤醒等待中的线程");
                    condition.signal();

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    log("释放对象：lock");
                    lockDemo.unlock();
                }
                log("线程结束");
            }
        };
        thread2.setName("thread02");
        thread2.start();


    }
}
